(function($) {
    var storage = new Sammy.Store({name: 'peoples', type: 'local'});

    var app = $.sammy('#content', function() {
        this.use('Template');
        this.use('Session');
        this.use('Form');
        
        this.helpers({                    
            displayContactsGroup: function() {
                $('#nav-contacts').addClass('active');
                
                id = this.params['id']
                class = 'contact-listitem';
                this.clearPane(2);

                // if #contacts-group doesn't exist, create it
                if (!$('#contacts-group').length) {
                    // first time activating contacts group pane: clear previous pane
                    this.clearPane(1);
                    $('#groups').append('<div id="contacts-group"></div>');
                    
                    context = this;     // set context
                    this.load('data/contacts.php')     // contacts.json
                        .then(function(contacts) {
                            contacts = jQuery.parseJSON(contacts);
                            // console.log(contacts);
                            $.each(contacts, function(i, contact) {
                                // must use "appendTo" to ensure stacking (otherwise each iteration would replace previous contact)
                                context.render('templates/contacts-listitem.template', {contact: contact, id: id}).appendTo(context.$element('#contacts-group'));
                            });

                        });
                }

                else {
                    activate(class, id);
                }

            }, // end displayContactsGroup()
            
            displayContactCard: function(id) {
                $(id).addClass('contactcard')
            }, // end displayContactsSlide()

            clearPane: function(panenum) {
                // 1: groups, 2: section, default: both
                node = '.pane';
                $(node).removeClass('contactcard');
                
                if (panenum == 1) node = '#groups';
                else if (panenum == 2) node = '#section';
                
                $(node).text('');
            } // end clearPane()
        });
        
        function checkLoggedIn(callback) {
            // TODO: better check of login (compare to db)
            if (!storage.get('userid')) {
                $('#container').hide();
                this.redirect('login.php?url=' + app.getLocation());
            }
            else {
                // TODO: check permissions
                // TODO: load contacts IF it's not already stored
                $('.nav').removeClass('active');
                
                callback();
            }
        }
        
        this.around(checkLoggedIn);
        
        var activate = function(class, id) {
            prefix = '#' + class + '-';   // hard and fast rule
            deactivate(class);
            if (id) {
                $(prefix + id).addClass('active');
            }
            // console.log($(prefix + id));
        };
        
        var deactivate = function(class) {
            // clear previous active states          
            $('.' + class).removeClass('active');           
        }
        

        // route mapping
        this.mapRoutes([
            // #ACTIVITY
            ['get', '#/', function(context) {
                $('#nav-activity').addClass('active');
                this.clearPane();
                
                // groups
                context.render('templates/activity-aside.template').appendTo(context.$element('#groups'));
                
                // section
                this.load('data/notes.json')
                    .then(function(notes) {
                        context.log('activity section');
                        $.each(notes, function(i, note) {
                            // must use "appendTo" to ensure stacking (otherwise each iteration would replace previous note)
                            context.render('templates/activity-note.template', {note: note}).appendTo(context.$element('#section'));
                        });
                    });
            }],
           
            // #CONTACTS
            ['get', '#/contacts', function(context) {
                this.displayContactsGroup();
            }],
            
            ['get', '#/contacts/add', function(context) {
                this.displayContactsGroup();
                
                // ...
            }],
            
            ['post', '#/contacts/submit', function(context) {
                this.displayContactsGroup();
                
                // http://kazimanzurrashid.com/posts/asp-dot-net-mvc-plus-sammy-dot-js-plus-mustache-dot-js-equalto-crazy-delicious
                /*  response = {
                        success: true || false, 
                        msg: (opt),                 // potential error msg
                        contact: 
                    } */
                $.post('data/contact-submit.php',
                    this.params.toHash(),
                    function(response) {
                        console.log(response);
                        
/*                        if (response.success) {
                            console.log(response);
                        }*/
                    });

/*                this.load('data/contact-submit.php?contact=' + this.params.toHash())
                    .then(function(contact) {
                       debug = contact;
                    });*/
            }],
            
            ['get', '#/contacts/:id', function(context) {
                this.displayContactsGroup();
                
                // section
                this.load('data/contact.php?id=' + this.params['id'])      // contact.json
                    .then(function(contact) {
                        contact = jQuery.parseJSON(contact);
                        context.render('templates/contact.template', 
                            {contact: contact[0]}).appendTo(context.$element('#section'));
                        context.displayContactCard('#section');
                    });
            }],
            
            ['get', '#/contacts/:id/edit', function(context) {
                this.displayContactsGroup();
                id = this.params['id'];
                
                // section
                this.load('data/contact.php?id=' + id)      // contact.json
                    .then(function(contact) {
                        contact = jQuery.parseJSON(contact);
                        context.render('templates/contact-form.template', 
                            {contact: contact[0]}, {escape_html: true}).appendTo(context.$element('#section'));
                    });
            }]
            
        ]); // end route mapping


    });

    // default start
    $(function() {
      app.run('#/');
    });

})(jQuery);
